package com.ll.app.exception;

import com.alibaba.fastjson.JSONObject;
import com.ll.base.dto.ApiResultDTO;
import com.ll.base.enums.ResultCodeEnum;
import com.ll.base.util.ScalarUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.UUID;

@Slf4j
@RestControllerAdvice
public class ExceptionController {
    /**
     *  校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResultDTO validationBodyException(MethodArgumentNotValidException exception){

    	//对校验错误信息进行封装，并输出到日志
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        String traceId = UUID.randomUUID().toString();
        if (result.hasErrors()) {
            String parmStr = null;
            if(result.getTarget() != null){
                parmStr =  JSONObject.toJSONString(result.getTarget());
            }
            log.error("TraceId {},参数校验失败 DTOName ：{},  \n  ------->value: {}", traceId, result.getObjectName(), parmStr);
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p ->{
                FieldError fieldError = (FieldError) p;
                errorMessage.append(fieldError.getDefaultMessage()).append(ScalarUtil.DEFAULT_STRING_SPLIT);
            });
            log.error("TraceId {},参数校验结果：{},  ",traceId, errorMessage.toString());
        }
        //封装错误到响应信息
        return ApiResultDTO.failure(ResultCodeEnum.PARAM_VALUE_INVALID.getCode(), errorMessage.toString());
    }
    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ApiResultDTO handleException(HttpRequestMethodNotSupportedException e) {
        ApiResultDTO response = ApiResultDTO.failure(ResultCodeEnum.PARAM_METHOD_ERROR.getCode(),"不支持' " + e.getMethod() + "'请求" );
        log.error("请求方式不支持 {}" , e.getMethod(), e);
        return response;
    }

    /**
     * 请求的数据格式错误的处理
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResultDTO handleException(HttpMessageNotReadableException e) {
        log.error("请求的数据格式错误 " , e);
        ApiResultDTO response = ApiResultDTO.failure(ResultCodeEnum.PARAM_CONTENT_TYPE_ERROR);
        return response;
    }
}
